<template>
  <div class="list-table">
    <el-form ref="queryForm" :model="queryParams" :inline="true">
      <el-form-item :label="$t('账套')">
        <el-select v-model="queryParams.fundAccountId" @change="changeLedgerPeriod">
          <el-option v-for="item in finFundAccountList" :key="item.id" :label="item.accountName" :value="item.id" />
        </el-select>
      <!-- {{ queryParams.yearMonth }} -->
      </el-form-item>
      <el-form-item :label="$t('周期')">
        <el-select v-model="queryParams.yearMonth" placeholder="请选择" @change="changePeriod">
          <el-option v-for="item in periodOptions" :key="item.id" :label="item.accountYearMonth" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('科目编码')">
        <el-input v-model="queryParams.subjectCode" :placeholder="$t('科目编码')" clearable />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="queryHandle">{{ $t('搜索') }}</el-button>
        <el-popover placement="right" width="400" trigger="click">
          <el-checkbox-group v-model="checkList" @change="handleCheckedChange">
            <el-checkbox label="0">期初余额为0不显示</el-checkbox>
            <el-checkbox label="1">无发生额且期初余额为0不显示</el-checkbox>
          </el-checkbox-group>
          <el-button slot="reference" icon="el-icon-setting" size="mini" />
        </el-popover>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="warning" icon="el-icon-download" size="mini" @click="exportHandle">{{ $t('导出') }}</el-button>
      </el-col>
    </el-row>
    <el-table v-loading="loading" :height="windowHeight" :data="dataList" border show-summary stripe style="width: 100%;margin-bottom: 20px;" :row-style="{ height: '42px' }">

      <el-table-column :label="$t('科目编码')" align="left" prop="subjectCode" width="140">
        <template slot-scope="scope">
          <span class="custom-cell">{{ scope.row.subjectCode }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('科目名称')" prop="subjectName" show-overflow-tooltip>
        <template slot-scope="scope">
          <el-button type="text" size="mini" @click="handleButtonClick(scope.row)">{{ scope.row.subjectName }}</el-button>
        </template>
      </el-table-column>
      <el-table-column label="期初余额" align="center">
        <el-table-column :label="$t('借方')" align="right" prop="begDebitAmount" width="140">
          <template slot-scope="scope">
            {{ formattedNumber(scope.row.begDebitAmount) }}
          </template>
        </el-table-column>
        <el-table-column :label="$t('贷方')" align="right" prop="begCreditAmount" width="140">
          <template slot-scope="scope">
            {{ formattedNumber(scope.row.begCreditAmount) }}
          </template>
        </el-table-column>
      </el-table-column>
      <el-table-column label="本期发生额" align="center">
        <el-table-column :label="$t('借方')" align="right" prop="accrualDebitAmount" width="140">
          <template slot-scope="scope">
            {{ formattedNumber(scope.row.accrualDebitAmount) }}
          </template>
        </el-table-column>
        <el-table-column :label="$t('贷方')" align="right" prop="accrualCreditAmount" width="140">
          <template slot-scope="scope">
            {{ formattedNumber(scope.row.accrualCreditAmount) }}
          </template>
        </el-table-column>
      </el-table-column>
      <el-table-column label="本年累计发生额" align="center">
        <el-table-column :label="$t('借方')" align="right" prop="accrualDebitAmount" width="140">
          <template slot-scope="scope">
            {{ formattedNumber(scope.row.yearDebitAmount) }}
          </template>
        </el-table-column>
        <el-table-column :label="$t('贷方')" align="right" prop="accrualCreditAmount" width="140">
          <template slot-scope="scope">
            {{ formattedNumber(scope.row.yearCreditAmount) }}
          </template>
        </el-table-column>
      </el-table-column>
      <el-table-column label="期末余额" align="center">
        <el-table-column :label="$t('借方')" align="right" prop="endDebitAmount" width="140" :formatter="cellFormatter">
          <template slot-scope="scope">
            <span :class="getCellColor(scope.row.endDebitAmount)">{{ formattedNumber(scope.row.endDebitAmount) }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('贷方')" align="right" prop="endCreditAmount" width="140" :formatter="cellFormatter">
          <template slot-scope="scope">
            <span :class="getCellColor(scope.row.endCreditAmount)">{{ formattedNumber(scope.row.endCreditAmount) }}</span>
          </template>
        </el-table-column>
      </el-table-column>
    </el-table>
    <el-dialog :title="$t(title)" :visible.sync="formOpen" :close-on-click-modal="false" :lock-scroll="false" custom-class="dialogForm" append-to-body>
      <accountDetail ref="accountDetail" />
    </el-dialog>
  </div>
</template>

<script>
import {
  mapState,
  mapActions
} from 'vuex'
import {
  findABReport,
  getLedgerPeriod
} from '@/api/fin/report/finReport'
import {
  getFundAccountYearMonthList
} from '@/api/fin/fundAccount/finFundAccount'
import accountDetail from './accountDetail.vue'

export default {
  components: {
    accountDetail
  },
  data() {
    return {
      visible: false,
      checkList: [],
      title: '科目',
      // 遮罩层
      loading: true,
      // 总条数
      total: 0,
      dataList: [],
      cacheDataList: [],
      fundLedgerOptions: [],
      periodOptions: [],
      finFundAccountList: [],
      // 是否显示弹出层
      formOpen: false,
      // 查询参数
      queryParams: {
        fundAccountId: undefined,
        yearMonth: undefined,
        subjectCode: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      fundAccountId: undefined,
      yearMonth: undefined,
      windowHeight: document.documentElement.clientHeight - 260 // 实时屏幕高度
    }
  },
  computed: {
    ...mapState('finReport', ['finQueryParams'])
  },
  created() {
    this.getFundAccountList()
  },
  methods: {
    ...mapActions('finReport', ['changeQueryParams']),
    getList() {
      this.loading = true
      findABReport(this.queryParams).then(response => {
        this.dataList = response.data
        this.cacheDataList = response.data
        this.handleCheckedChange(this.checkList)
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    /** 搜索按钮操作 */
    queryHandle() {
      // this.queryParams.pageNum = 1
      this.getList()

      // this.checkList = []
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.queryHandle()
    },
    handleButtonClick(row) {
      this.title = '科目:' + row.subjectCode + '  ' + row.subjectName
      this.formOpen = true
      this.$nextTick(() => {
        const data = {
          fundAccountId: this.queryParams.fundAccountId,
          yearMonth: this.queryParams.yearMonth,
          subjectCode: row.subjectCode
        }
        this.$refs.accountDetail.init(data)
      })
    },
    // 获取基金账套列表
    getFundAccountList() {
      getFundAccountYearMonthList({}).then(response => {
        this.finFundAccountList = response.data
        if (this.finFundAccountList && this.finFundAccountList.length > 0) {
          const item = this.finFundAccountList[0]
          // 初始化加载默认账套时，查询科目
          this.queryParams.fundAccountId = item.id
          this.queryParams.yearMonth = item.carryoverRecordId
          this.fundAccountId = item.id
          this.yearMonth = item.carryoverRecordId
          getLedgerPeriod(item.id).then(res => {
            this.periodOptions = res.data
          })
          if (this.finQueryParams.accountId && this.finQueryParams.yearMonth) {
            getLedgerPeriod(this.finQueryParams.accountId).then(res => {
              this.periodOptions = res.data
            })
            this.queryParams.fundAccountId = this.finQueryParams.accountId
            this.queryParams.yearMonth = this.finQueryParams.yearMonth
          }
          this.getList()
        } else {
          this.loading = false
        }
      })
    },
    changeLedgerPeriod(val) {
      this.fundAccountId = val
      getLedgerPeriod(val).then(res => {
        this.periodOptions = res.data
      })
      this.finFundAccountList.forEach(item => {
        if (val === item.id) {
          this.queryParams.yearMonth = item.carryoverRecordId
          this.changeQueryParams(this.queryParams)
        }
      })
    },
    // 导出
    exportHandle() {
      this.$confirm(this.$t('是否导出Excel?'), this.$t('警告'), {
        confirmButtonText: this.$t('确定'),
        cancelButtonText: this.$t('取消'),
        type: 'warning'
      }).then(() => {
        const queryParams = this.queryParams
        this.downLoadExcelPost('/fin/finReport/exportABExcel', queryParams).then(response => {
          if (response.code === 200) {
            this.msgSuccess(this.$t(response.msg))
          } else {
            this.msgError(this.$t(response.msg))
          }
        })
      }).catch(() => {})
    },
    changePeriod(val) {
      this.yearMonth = val
      this.changeQueryParams(this.queryParams)
    },
    formatMoney(value) {
      if (value) {
        if (!isNaN(value)) {
          return parseFloat(value).toFixed(2)
        } else {
          return value
        }
      } else {
        return ''
      }
    },
    formattedNumber(val) {
      if (val === 0 || val === '0') return ''
      if (val != null && !isNaN(Number(val))) {
        if (typeof val === 'string') {
          return parseFloat(val).toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',')
        } else if (typeof val === 'number') {
          return val.toLocaleString('en-US', {
            style: 'decimal',
            minimumFractionDigits: 2,
            maximumFractionDigits: 2
          })
        }
      } else {
        return val
      }
    },
    cellFormatter(row, column, cellValue) {
      return {
        style: cellValue < 0 ? 'color: #ea8685;' : ''
      }
    },
    getCellColor(cellValue) {
          return cellValue < 0 ? 'fail-cell' : ''
    },
    handleCheckedChange(val) {
      if (val.includes('1')) {
        this.dataList = this.cacheDataList
         // 发生额为0 不显示
        // accrualDebitAmount accrualCreditAmount
        this.dataList = this.dataList.filter(item => {
          return (
            (this.isNonZeroNumber(item.begDebitAmount) || this.isNonZeroNumber(item.begCreditAmount)) ||
            (this.isNonZeroNumber(item.accrualDebitAmount) || this.isNonZeroNumber(item.accrualCreditAmount))
          )
        })
       } else if (val.includes('0')) {
          this.dataList = this.cacheDataList
          this.dataList = this.dataList.filter(item => this.isNonZeroNumber(item.begDebitAmount) || this.isNonZeroNumber(item.begCreditAmount))
      } else {
          this.dataList = this.cacheDataList
      }
    },
    isNonZeroNumber(value) {
      // 检查变量是否为数字
      if (value == null || value === '' || value === 0) {
        return false
      } else {
        return true
      }
    }
  }
}
</script>

<style scoped>
.success-cell {
  color: green;
}
.fail-cell {
  color: #ea8685;
}
.cell {
  height: 54px !important;
}

.bold-text {
  font-weight: bold;
  font-size: 14px;
}

.indented-text {
  text-indent: 20px !important;
}

.custom-cell {
  white-space: break-spaces !important;
}

.el-table .el-table__body-wrapper tbody tr td {
  text-indent: 20px;
}
</style>
